﻿using Breeze.WebApi;
using LunchLearn.WebApi.Infrastructure.Notifications;
using LunchLearn.WebApi.Domain;
using LunchLearn.WebApi.Repository;

namespace LunchLearn.WebApi.Infrastructure.TrackingServices
{
    public class OrderTrackingService : IChangeTrackingService
    {
        private readonly INotificationBridge _messageBridge;

        public OrderTrackingService(INotificationBridge messageBridge)
        {
            _messageBridge = messageBridge;
        }

        public void Track(EntityInfo entityInfo, LunchLearnContext context)
        {
            if (entityInfo.EntityState == EntityState.Added)
            {
                SendNewOrderNotification(entityInfo.Entity as Order);
            }
            if (entityInfo.EntityState == EntityState.Modified)
            {
                var isActiveSpec = new IsActiveSpec();
                if (!isActiveSpec.IsSatisifedBy(entityInfo.Entity as Order))
                    SendDeletedOrderNotification(entityInfo.Entity as Order);
            }
        }

        private void SendDeletedOrderNotification(Order order)
        {
            _messageBridge.SendNotification(new Notification(NotificationType.Deleted, order,"Order {0} has been deleted", order.ReferenceId.ToString()));
        }

        private void SendNewOrderNotification(Order order)
        {
            _messageBridge.SendNotification(new Notification(NotificationType.Added, order, "New order from {0}", order.ReferenceId.ToString()));
        }
    }
}
